package com.yale.elasticsearch.service.query;

import com.yale.elasticsearch.dto.WildcardQueryDTO;
import com.yale.elasticsearch.model.entity.UserInfo;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.json.JsonData;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 通配符查询
 */
@Service
@Slf4j
public class WildcardQueryService {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    /**
     * 查询所有以 “三” 结尾的姓名
     * <p>
     * *：表示多个字符（0个或多个字符）
     * ?：表示单个字符
     */
    public Object wildcardQuery(WildcardQueryDTO wildcardQueryDTO) {
        Object result = "";
        try {
            // 构建 Wildcard 查询条件
            Query wildcardQuery = Query.of(q -> q
                    .wildcard(w -> w
                            .field(wildcardQueryDTO.getField())
                            .value(wildcardQueryDTO.getValue())
                    )
            );

            // 创建查询请求对象
            SearchRequest searchRequest = SearchRequest.of(s -> s
                    .index(wildcardQueryDTO.getIndexName())
                    .query(wildcardQuery)
            );

            // 执行查询
            SearchResponse<JsonData> searchResponse = elasticsearchClient.search(searchRequest, JsonData.class);
            List<UserInfo> userInfoList = new ArrayList<>();
            // 处理响应结果
            if (searchResponse.hits().total().value() > 0) {
                searchResponse.hits().hits().forEach(hit -> {
                    // 将 JSON 转换成对象
                    UserInfo userInfo = JSON.parseObject(hit.source().toJson().toString(), UserInfo.class);
                    userInfoList.add(userInfo);
                    // 输出查询信息
                    log.info("打印查询结果：{}",JSON.toJSONString(userInfo));
                });
            }

            result = JSON.toJSONString(userInfoList);

        } catch (IOException e) {
            log.error("Error executing search request: {}" , e.getMessage());
        }
        return result;
    }

}
